import cv2


face_detector = cv2.CascadeClassifier(r'.\haarcascade_frontalface_default.xml')
mask_detector = cv2.CascadeClassifier(r'.\xml\cascade.xml')
cap = cv2.VideoCapture(0)
while True:
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_detector.detectMultiScale(gray, 1.1, 5, minSize=(90, 90))
    for (x, y, w, h) in faces:
        mask = False
        # cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 255), 2)
        ds = 0.3
        dh = int((y + h) * ds / 2)
        dw = int((x + w) * ds / 2)
        face = gray[y - dh:y + h + dh, x - dw:x + w + dw]
        mask_face = mask_detector.detectMultiScale(face, 1.1, 3, minSize=(100, 100))
        for( x2, y2, w2, h2 ) in mask_face:
            # cv2.rectangle(img, (x2, y2), (x2 + w2, y2 + h2), (0, 0, 255), 2)
            # cv2.putText(img, 'mask', (x2, y2 - 2), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (255, 255, 255), 2)
            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
            cv2.putText(img, 'mask', (x, y - 2), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (255, 255, 255), 2)
            mask = True
        if mask == False:
            cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 255), 2)
            cv2.putText(img, 'no_mask', (x, y - 2), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (255, 0, 0), 2)
            
    cv2.imshow('mask', img)
    cv2.waitKey(3)
cap.release()
cap.destoryAllWindows()
            
